package com.example.partner.activity.home;

import static com.example.partner.common.ConfigConstant.BASE_URL;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager2.widget.ViewPager2;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.partner.common.BaseResponse;

import com.bumptech.glide.Glide;
import com.example.partner.R;

import com.example.partner.adapter.ConcernViewPagerAdapter;
import com.example.partner.common.UserInfoViewModel;
import com.example.partner.service.FollowService;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class UserInfoActivity extends AppCompatActivity {
    ImageView avatar;
    TextView usernameTextView;
    ViewPager2 viewPager;
    TabLayout tabLayout;
    String userAccount,avatarUrl,username;
    Long userId,loginUserId;
    Button followButton;
    private FollowService followService;
    Boolean isFollow;
    ConcernViewPagerAdapter viewPagerAdapter;
    private UserInfoViewModel viewModel;



    @Override
    public SharedPreferences getSharedPreferences(String name, int mode) {
        return super.getSharedPreferences(name, mode);
    }



    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_info);
        avatar = findViewById(R.id.avatarUrl);
        usernameTextView = findViewById(R.id.username);
        viewPager = findViewById(R.id.concernViewPager);
        tabLayout = findViewById(R.id.concernTabLayout);
        followButton = findViewById(R.id.button);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL) // 更换为您的服务器URL
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        followService = retrofit.create(FollowService.class);
        SharedPreferences sharedPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
        loginUserId = sharedPreferences.getLong("userId", -1);
        viewModel = new ViewModelProvider(this).get(UserInfoViewModel.class);
        Intent intent = getIntent();
        userAccount = intent.getStringExtra("userAccount");
        username = intent.getStringExtra("username");
        avatarUrl =  intent.getStringExtra("avatarUrl");
        userId = intent.getLongExtra("selectedUserId",-1);
        viewModel.setUserId(userId);
        viewModel.setUserAccount(userAccount);
        viewModel.setAvatarUrl(avatarUrl);
        viewModel.setUsername(username);
        usernameTextView.setText(username);
        Glide.with(this).load(avatarUrl).into(avatar);
        // 在这里进行与 Activity 相关的操作
        // 在 onCreate 中设置 ViewPager 和 TabLayout
        viewPagerAdapter = new ConcernViewPagerAdapter(this);
        viewPager.setAdapter(viewPagerAdapter);
        new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> {
            // 设置标签的文本
            switch (position) {
                case 0:
                    tab.setText("用户信息");
                    break;
                case 1:
                    tab.setText("共同关注");
                    break;
            }
        }).attach();
        followOrNot(userId,loginUserId);
        // 添加 TabLayout 的 Tab 选择监听器

        followButton.setOnClickListener(view -> {
            submitFollow(userId);

        });

        avatar.setOnClickListener(view -> {
            // 启动新的Activity或DialogFragment来显示图片
            Intent avatarIntent = new Intent(UserInfoActivity.this, ImageDisplayActivity.class);
            // 如果图片是从网络加载的，传递图片的URL
            avatarIntent.putExtra("image_url", avatarUrl);
            startActivity(avatarIntent);
        });

    }

    private void followOrNot(Long userId,Long loginUserId) {
        followService.isFollow(userId,loginUserId).enqueue(new Callback<BaseResponse<Boolean>>() {
            @Override
            public void onResponse(Call<BaseResponse<Boolean>> call, Response<BaseResponse<Boolean>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    // 处理成功的响应
                    isFollow = response.body().getData();
                    if (isFollow){
                        followButton.setText("取消关注");
                    }
                    // 更新UI或处理数据
                } else {
                    // 处理错误情况
                }
            }

            @Override
            public void onFailure(Call<BaseResponse<Boolean>> call, Throwable t) {
                // 网络错误处理
                t.printStackTrace();
            }
        });

    }
    private void submitFollow(Long userId) {
        followService.follow(userId,loginUserId,isFollow).enqueue(new Callback<BaseResponse<Boolean>>() {
            @Override
            public void onResponse(Call<BaseResponse<Boolean>> call, Response<BaseResponse<Boolean>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    // 处理成功的响应
                    if (response.body().data && isFollow == false){
                        // 创建AlertDialog
                        new AlertDialog.Builder(UserInfoActivity.this)
                                .setTitle("关注") // 设置对话框标题
                                .setMessage("关注成功") // 设置要显示的消息
                                .setPositiveButton("确定", (dialog, which) -> {
                                    // 用户点击确定按钮后的操作
                                })
                                .show();
                        isFollow = true;
                        followButton.setText("取消关注");

                    }else {
                        new AlertDialog.Builder(UserInfoActivity.this)
                                .setTitle("取消关注") // 设置对话框标题
                                .setMessage("已取消关注") // 设置要显示的消息
                                .setPositiveButton("知道了", (dialog, which) -> {
                                    // 用户点击确定按钮后的操作
                                })
                                .show();
                        isFollow = false;
                        followButton.setText("关注");

                    }

                    // 更新UI或处理数据
                } else {
                    // 处理错误情况
                }
            }

            @Override
            public void onFailure(Call<BaseResponse<Boolean>> call, Throwable t) {
                // 网络错误处理
                t.printStackTrace();
            }
        });


    }



}

